#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>


 
  struct ListNode {
      int val;
      ListNode *next;
      ListNode() : val(0), next(nullptr) {}
      ListNode(int x) : val(x), next(nullptr) {}
      ListNode(int x, ListNode *next) : val(x), next(next) {}
  };

    ListNode* reverseKGroup(ListNode* head, int k) {
        //if (head == nullptr || head->next)return head;
        ListNode* c = head;
        int count = 0;
        while (c)
        {
            count++;
            c = c->next;
        }
        int n = count / k;


        ListNode* head1 = new ListNode(0);
        ListNode* cur = head;
        ListNode* prev = head1;
        for (int i = 0; i < n; i++)
        {

            ListNode* tmp = cur;
            for (int j = 0; j < k; j++)
            {

                ListNode* next = cur->next;
                cur->next = prev->next;
                prev->next = cur;

                cur = next;
            }
            prev = tmp;

        }
        prev->next = cur;
        prev = head1->next;
        delete head1;
        return prev;
    }

int main()
{
    ListNode* n1 = new ListNode(1);
    ListNode* n2 = new ListNode(2);
    ListNode* n3 = new ListNode(3);
    ListNode* n4 = new ListNode(4);
    ListNode* n5 = new ListNode(5);
    n1->next = n2;
    n2->next = n3;
    n3->next = n4;
    n4->next = n5;

    ListNode* head = reverseKGroup(n1, 2);

    ListNode* cur =head;
    while (cur)
    {
        std::cout << cur->val << " ";
        cur = cur->next;
    }

    return 0;
}